//
//  EmoticonsController.swift
//  emoticon模块代码
//
//  Created by rong on 15/7/8.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit

//可充用标识符
private let EmoticonKeyBoardIdentifier = "EmoticonKeyBoardIdentifier"

class EmoticonsController: UIViewController {
    
    //选中的表情回调
    var didSelectedEmoticonCallBack: (emoticon: Emoticon) -> ()
    
    //外界调用的 构造函数，传入闭包  
    init(didSelectedEmoticon: (emoticon: Emoticon) -> ()) {
        
        //把传入的闭包暂时 记录 下来
        didSelectedEmoticonCallBack = didSelectedEmoticon
        
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func selectItems(item: UIBarButtonItem) {
        //print(item.tag
        
        let path = NSIndexPath(forItem: 0, inSection: item.tag)
        emoticonsView.scrollToItemAtIndexPath(path, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.redColor()
        
        //此时打印的结果为  (0.0, 0.0, 375.0, 667.0)
        //print(view.frame)
        
        prepareForUI()
        
    }
    
    //准备自定义键盘的整体 UI 布局
    private func prepareForUI() {
        
        view.addSubview(toolBar)
        view.addSubview(emoticonsView)
        
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        emoticonsView.translatesAutoresizingMaskIntoConstraints = false
        
        //定义约束
        var cons = [NSLayoutConstraint]()
        
        let viewDict = ["emoticonsView": emoticonsView, "toolBar": toolBar]
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[emoticonsView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[emoticonsView]-0-[toolBar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
        
        //添加约束
        view.addConstraints(cons)
        
        prepareForToolBar()
        prepareForCollectionView()
    }
    
    //准备toolbar
    private func prepareForToolBar() {
        
        toolBar.tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        
        var index = 0
        
        // ["最近", "默认", "emoji", "浪小花"]
        for str in packages {
            
            let item = UIBarButtonItem(title: str.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "selectItems:") //Selector("selectItems:")
            item.tag = index++
            
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolBar.items = items
    }
    
    private func prepareForCollectionView() {
        
        emoticonsView.backgroundColor = UIColor.whiteColor()
        
        emoticonsView.pagingEnabled = true
        
        emoticonsView.dataSource = self
        
        emoticonsView.delegate = self
        
        emoticonsView.registerClass(EmoticonsCell.self, forCellWithReuseIdentifier: EmoticonKeyBoardIdentifier)
    }
   
    
    //懒加载控件
    private lazy var toolBar = UIToolbar()
    private lazy var layout:EmoticonsLayout = EmoticonsLayout()
    private lazy var emoticonsView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    //表情数组
    //private lazy var packages: [EmoticonPackage] = EmoticonPackage.packages()
    private lazy var packages: [EmoticonPackage] = EmoticonPackage.packageList
}


extension EmoticonsController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonKeyBoardIdentifier, forIndexPath: indexPath) as! EmoticonsCell
        
        //这里设置颜色，这里不设置颜色，不会看见cell 
        //cell.backgroundColor = indexPath.item%2==0 ? UIColor.redColor() : UIColor.greenColor()
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.row]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let emoticon = packages[indexPath.section].emoticons![indexPath.row]
        
        print("选中了表情！！！")
        //print("\(emoticon.chs) \(emoticon.emoji)")
        
        //判断表情符号是否有效
        if emoticon.chs != nil || emoticon.emoji != nil {
            emoticon.times++
            
            //将表情添加 “最近的” emoticon数组
            packages[0].addRecentUseEmoticon(emoticon)
        }
        
        didSelectedEmoticonCallBack(emoticon: packages[indexPath.section].emoticons![indexPath.row])
    }
}

